<?php

/**
 * 客服聊天模块
 * @version $Id: Note.php 567 2015-02-05 11:52:51Z karson $
 */
class ChatModel Extends Model {

    public $key = "";

    /**
     * 构造函数
     */
    public function __construct() {
        parent::__construct();
    }

    public function get($id) {
        return $this->db->one("SELECT * FROM {pre}chat WHERE id = ?", array($id));
    }

    public function chatlist($offset = 0) {
        $chatlist = array();
        $where = "";
        if ($offset) {
            $where = " AND createtime <" . intval($offset);
        }
        $this->db->query("SELECT *, COUNT(*) AS messages FROM {pre}chat WHERE user_id = ? AND status = ? {$where} GROUP BY user_id "
            . "ORDER BY createtime DESC LIMIT 10", array($this->user->id, 'normal'));
        while ($row = $this->db->fetch()) {
            $row['offset'] = $row['createtime'];
            $chatlist[] = $row;
        }
        $this->user->renderdata($chatlist);
        return $chatlist;
    }

    public function info($last_chat_id = 0, $offset = 0) {
        $chatlist = array();
        $where = " AND id >" . intval($last_chat_id);
        if ($offset) {
            $where = " AND id < " . intval($offset);
        }
        $this->db->query("SELECT * FROM {pre}chat WHERE user_id = ? AND status = ? {$where} ORDER BY id DESC LIMIT 10", array($this->user->id, 'normal'));
        while ($row = $this->db->fetch()) {
            $row['offset'] = $row['id'];
            $chatlist[] = $row;
        }
        $this->user->renderdata($chatlist);
        return $chatlist;
    }

    public function post($content) {
        $params = array(
            'user_id' => $this->user->id,
            'sender_role' => 'user',
            'content' => $content,
            'readtime' => time(),
            'createtime' => time(),
            'status' => 'normal'
        );
        $this->db->insert("{pre}chat", $params);
        return TRUE;
    }

}
